import React, {useState, useEffect, useLayoutEffect, useCallback} from 'react';
import {
  StyleSheet,
  View,
  Text,
  SafeAreaView,
  FlatList,
  Image,
  TouchableOpacity,
} from 'react-native';
import {navigate} from 'utils/navigationService';
//import { get } from 'utils/request';
//import qs from 'qs';
import {EventType, ResponseType} from 'types';
import dayjs from 'dayjs';
import {useDispatch, useSelector} from 'react-redux';
import actions from 'reduxState/actions';
import {get} from 'utils/request';
import {channel} from '@redux-saga/core';
import qs from 'qs';
import {t} from 'i18n-js';
import lang from 'lang';
import {DrawerActions} from '@react-navigation/native';
import VirScroll, {
  ResponseListType,
  VirgetParamType,
} from 'components/VirScroll';
import api from 'service';
const limit = 10;

interface Props {
  queryFn?: (props: VirgetParamType) => Promise<ResponseListType>;
}

function EventList({queryFn}: Props) {
  const dataChangeHandle = React.useRef((param: []) => {});
  const currentData = React.useRef([]);
  const dispatch = useDispatch();
  const getData =
    queryFn ||
    async function getData({offset}: VirgetParamType) {
      const {data}: ResponseType = await api.getEventList(
        offset,
        limit,
        String(channelId),
      );
      console.log('d', data);

      return {list: data.events, hasMore: data.hasMore};
    };
  function getGoBtn(
    isTrue: boolean,
    count: number,
    item: EventType,
    idx: number,
  ) {
    const url = isTrue
      ? require('assets/icons/check.png')
      : require('assets/icons/check-outline.png');
    return (
      <TouchableOpacity
        onPress={async () => {
          // like 改变本地数据
          if (isTrue) {
            try {
              await api.delJoinEvent(item.id);
            } catch (error) {}
            (currentData.current[idx] as EventType).me_going = false;
            (currentData.current[idx] as EventType).goings_count--;
          } else {
            try {
              await api.joinEvent(item.id);
            } catch (error) {}
            (currentData.current[idx] as EventType).me_going = true;
            (currentData.current[idx] as EventType).goings_count++;
          }
          dataChangeHandle.current(currentData.current as []);
        }}>
        <View style={styles.metaBtn}>
          <Image style={styles.metaIcon} source={url} />
          <Text>{isTrue ? 'I am going!' : `${count} Going`}</Text>
        </View>
      </TouchableOpacity>
    );
  }
  function getLikeBtn(
    isTrue: boolean,
    count: number,
    item: EventType,
    idx: number,
  ) {
    const url = isTrue
      ? require('assets/icons/like.png')
      : require('assets/icons/like-outline.png');
    return (
      <TouchableOpacity
        onPress={async () => {
          // like 改变本地数据
          if (isTrue) {
            try {
              await api.dellikeEvent(item.id);
            } catch (error) {}
            (currentData.current[idx] as EventType).me_likes = false;
            (currentData.current[idx] as EventType).likes_count--;
          } else {
            try {
              await api.likeEvent(item.id);
            } catch (error) {}
            (currentData.current[idx] as EventType).me_likes = true;
            (currentData.current[idx] as EventType).likes_count++;
          }
          dataChangeHandle.current(currentData.current as []);
        }}>
        <View style={styles.metaBtn}>
          <Image style={styles.metaIcon} source={url} />
          <Text>{isTrue ? 'I like it' : `${count} Likes`}</Text>
        </View>
      </TouchableOpacity>
    );
  }
  function renderItem({item, index}: {item: EventType; index: number}) {
    const {
      createdAt,
      name,
      description,
      creator,
      channel,
      images,
      me_going,
      goings_count,
      me_likes,
      likes_count,
    } = item;

    return (
      <View style={styles.listRow} key={item.id}>
        <View>
          <View style={styles.itemHeaderContainer}>
            <View style={styles.creatorContainer}>
              <Image
                style={styles.creatorAvatar}
                source={{uri: creator?.avatar}}
              />
              <Text style={styles.creatorName}>{creator.username}</Text>
            </View>
            <Text style={styles.channelName}>{channel?.name}</Text>
          </View>
          <View style={styles.itemHSubContainer}>
            <View style={styles.subLeft}>
              <Text style={styles.itemTitle}>{name}</Text>
              <View style={styles.itemTimeContainer}>
                <Image
                  style={styles.timeIcon}
                  source={require('assets/icons/time.png')}
                />
                <Text style={styles.timestamp}>
                  {dayjs(createdAt).format('DD MMM YYYY HH:mm')}
                </Text>
              </View>
            </View>
            {images && images.length > 0 && (
              <Image style={styles.image} source={{uri: images[0]}} />
            )}
          </View>
          {!!description && (
            <Text
              style={styles.desc}
              onPress={() => {
                // 存储当前选中详情并跳转到详情页
                dispatch(actions.setDetail(item));
                navigate('DetailsScreen');
              }}>
              {description}
            </Text>
          )}
          <View style={styles.metaTextContainer}>
            {getGoBtn(me_going, goings_count, item, index)}
            {getLikeBtn(me_likes, likes_count, item, index)}
          </View>
        </View>
      </View>
    );
  }

  const renderEmpty = () => {
    return (
      <View style={styles.emptyContainer}>
        <Image
          style={styles.image}
          source={require('assets/icons/no-activity.png')}
        />
        <Text style={styles.emptyTip}>No activity found</Text>
      </View>
    );
  };

  return (
    <VirScroll
      freshForce={getData}
      autoTop={true}
      getDataFn={getData}
      keyExtractor={(item: {id: any}) => String(item.id)}
      renderItem={renderItem}
      ListEmptyComponent={renderEmpty}
      changeItem={(origindata, change) => {
        currentData.current = origindata;
        dataChangeHandle.current = change;
      }}
    />
  );
}
const styles = StyleSheet.create({
  headerIconContainer: {
    paddingLeft: 20,
  },
  headerIcon: {
    width: 24,
    height: 24,
  },
  container: {
    flex: 1,
    backgroundColor: '#efefef',
  },
  listRow: {
    overflow: 'hidden',
    marginHorizontal: 15,
    paddingVertical: 16,
    borderBottomWidth: 1,
    borderBottomColor: '#E8E8E8',
  },
  itemHeaderContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    paddingBottom: 10,
  },
  creatorContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  creatorAvatar: {
    width: 20,
    height: 20,
    borderRadius: 10,
  },
  creatorName: {
    marginLeft: 8,
    fontSize: 12,
    fontWeight: 'bold',
    color: '#67616D',
  },
  channelName: {
    paddingVertical: 3,
    paddingHorizontal: 8,
    fontSize: 12,
    lineHeight: 12,
    color: '#D3C1E5',
    borderStyle: 'solid',
    borderWidth: 1,
    borderRadius: 10,
    borderColor: '#D3C1E5',
  },
  itemHSubContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 12,
  },
  subLeft: {flex: 1},
  itemTitle: {
    fontSize: 18,
    color: '#453257',
    fontWeight: 'bold',
  },
  itemTimeContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: 8,
  },
  timeIcon: {
    width: 12,
    height: 12,
  },
  timestamp: {
    marginLeft: 5,
    fontSize: 12,
    color: '#8560A9',
  },
  imagesContainer: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    width: 300,
  },
  image: {
    width: 64,
    height: 64,
    resizeMode: 'cover',
  },
  desc: {
    marginBottom: 8,
    fontSize: 14,
    color: '#67616D',
  },
  metaTextContainer: {
    flexDirection: 'row',
  },
  metaBtn: {
    flexDirection: 'row',
    alignItems: 'center',
    marginRight: 30,
  },
  metaIcon: {
    marginRight: 6,
    width: 12,
    height: 12,
  },
  emptyContainer: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 188,
  },
  emptyTip: {
    marginTop: 14,
    color: '#BABABA',
  },
});
export default EventList;
